package com.huahai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huahai.common.ErrorCode;
import com.huahai.common.ResultUtils;
import com.huahai.constant.RedisConstant;
import com.huahai.enums.TeamStatusEnum;
import com.huahai.exception.BusinessException;
import com.huahai.mapper.TeamMapper;
import com.huahai.pojo.dto.TeamJoinDTO;
import com.huahai.pojo.dto.TeamQueryDTO;
import com.huahai.pojo.dto.TeamUpdateDTO;
import com.huahai.pojo.entity.Team;
import com.huahai.pojo.entity.User;
import com.huahai.pojo.entity.UserTeam;
import com.huahai.pojo.vo.TeamUserVO;
import com.huahai.service.TeamService;
import com.huahai.service.UserService;
import com.huahai.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {


    @Resource
    private UserTeamService userTeamService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private UserService userService;

    private static final String CREATE_TEAM_LOCK = "createTeam:";
    private static final String JOIN_TEAM_KEY = "joinTeam:";

    private static final String LOCK_KEY = "lock";

    // 定义用户最大创建和加入的队伍数量
    private static final long USER_JOIN_MAX_NUM = 5L;

    /**
     * 创建队伍
     *
     * @param team
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 开启事务注解
    public Long saveTeam(Team team, User loginUser) {
        // 1. 判断请求参数是否为空
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 判断用户是否登录
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Long userId = loginUser.getId();
        // 获取分布式锁
        String lockKey = RedisConstant.PROJECT_KEY + RedisConstant.TEAM_KEY + CREATE_TEAM_LOCK + LOCK_KEY + userId;
        RLock lock = redissonClient.getLock(lockKey);
        // 获取锁
        long waitTime = 1000L;
        long leaseTime = 30L;
        try {
            boolean lockResult = lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            if (!lockResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍过于频繁，请稍后重试");
            }
            // 3. 判断创建队伍的参数是否合法
            checkTeamCreateRules(team, userId);
            // 4. 插入队伍数据到队伍表
            team.setId(null);
            // 将队长id设为创建队伍用户id
            team.setUserId(userId);
            boolean teamResult = this.save(team);
            if (!teamResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍失败");
            }
            // 5. 插入队伍数据到用户队伍关系表
            UserTeam userTeam = new UserTeam();
            userTeam.setUserId(userId);
            userTeam.setTeamId(team.getId());
            userTeam.setJoinTime(LocalDateTime.now());
            boolean userTeamResult = userTeamService.save(userTeam);
            if (!userTeamResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建队伍失败");
            }
            // 6. 返回创建的队伍id
            return team.getId();
        } catch (InterruptedException e) {
            log.error("创建队伍异常: {}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            // 如果释放的锁属于当前线程就释放锁
            boolean isThreadLock = lock.isHeldByCurrentThread();
            if (isThreadLock) {
                try {
                    lock.unlock();
                } catch (Exception e) {
                    log.error("unlock error:", e);
                }
            }
        }
    }

    /**
     * 创建队伍参数校验
     *
     * @param team
     * @param userId
     */
    private void checkTeamCreateRules(Team team, Long userId) {
        // 3. 校验队伍信息
        // 3.1 1 < 队伍最大人数 <= 20
        int maxNum = Optional.ofNullable(team.getMaxNum()).orElse(0);
        if (maxNum < 1 || maxNum > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数不符合要求");
        }
        // 3.2 队伍标题 <= 20
        String name = team.getName();
        if (StringUtils.isBlank(name) || name.length() > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍标题过长");
        }
        // 3.3 队伍描述 <= 512
        String description = team.getDescription();
        if (StringUtils.isNotBlank(description) && description.length() > 512) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述过长");
        }
        // 3.4 status是否公开（int）不传默认为0
        TeamStatusEnum status = TeamStatusEnum.getEnumByValue(team.getStatus());
        if (status == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态错误");
        }
        // 如果status=2，一定要设置密码，密码<= 32
        if (status.equals(TeamStatusEnum.SECRET)) {
            if (StringUtils.isBlank(team.getPassword()) || team.getPassword().length() > 32) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码设置错误");
            }
        }
        // 3.5 超时时间 > 当前时间
        LocalDateTime expireTime = team.getExpireTime();
        if (expireTime != null && LocalDateTime.now().isAfter(expireTime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间设置有误");
        }
        // 3.6 校验用户创建队伍是否超过5个
        // 为了防止用户在短时间内创建多个队伍，导致数据库读取有误，这里使用分布式锁解决
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        long teamCreateCount = this.count(queryWrapper);
        if (teamCreateCount >= 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户创建的队伍已满");
        }
    }

    /**
     * 根据查询参数查询队伍列表
     *
     * @param teamQueryDTO
     * @param isAdmin
     * @return
     */
    @Override
    public List<TeamUserVO> listTeams(TeamQueryDTO teamQueryDTO, boolean isAdmin, User loginUser) {
        // 1. 创建查询条件
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        // 2. 组合查询条件
        if (teamQueryDTO != null) {
            checkTeamQueryRules(teamQueryDTO, queryWrapper, isAdmin, loginUser);
        }
        // 3. 不展示过期时间小于现在的队伍（过滤）
        queryWrapper.and(qw -> {
            qw.gt("expireTime", new Date()).or().isNull("expireTime");
        });
        // 4. 查询队伍信息
        List<Team> teamList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(teamList)) {
            return new ArrayList<>();
        }
        // 5. 关联查询创建人的信息
        List<TeamUserVO> teamUserVOList = new ArrayList<>();
        for (Team team : teamList) {
            Long userId = team.getUserId();
            if (userId == null) {
                continue;
            }
            TeamUserVO teamUserVO = new TeamUserVO();
            User user = userService.getById(userId);
            // 用户脱敏
            User safetyUser = userService.getSafetyUser(user);
            if (safetyUser != null) {
                // 封装TeamUserVO列表
                BeanUtils.copyProperties(team, teamUserVO);
                BeanUtils.copyProperties(safetyUser, teamUserVO.getUser());
            }
            // TODO 关联队伍其他人信息
            teamUserVOList.add(teamUserVO);
        }
        //  6. 返回
        return teamUserVOList;
    }

    /**
     * 队伍查询参数校验
     *
     * @param teamQueryDTO
     * @param queryWrapper
     */
    private static void checkTeamQueryRules(TeamQueryDTO teamQueryDTO, QueryWrapper<Team> queryWrapper, boolean isAdmin, User loginUser) {
        // 2.1 队伍id
        Long teamId = teamQueryDTO.getId();
        if (teamId != null && teamId > 0) {
            queryWrapper.eq("id", teamId);
        }
        // 2.2 队伍id列表
        List<Long> idList = teamQueryDTO.getIdList();
        if (!CollectionUtils.isEmpty(idList)) {
            queryWrapper.in("id", idList);
        }
        // 2.3 队伍名称
        String teamName = teamQueryDTO.getName();
        if (StringUtils.isNotBlank(teamName)) {
            queryWrapper.like("name", teamName);
        }
        // 2.4 队伍描述
        String description = teamQueryDTO.getDescription();
        if (StringUtils.isNotBlank(description)) {
            queryWrapper.like("description", description);
        }
        // 2.5 同时查询队伍名称和描述
        String searchText = teamQueryDTO.getSearchText();
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> {
                qw.like("name", searchText).or().like("description", searchText);
            });
        }
        // 2.6 队伍最大人数
        Integer maxNum = teamQueryDTO.getMaxNum();
        if (maxNum != null && maxNum > 0) {
            queryWrapper.eq("maxNum", maxNum);
        }
        // 2.7 队伍队长id
        Long userId = teamQueryDTO.getUserId();
        if (userId != null && userId > 0) {
            queryWrapper.eq("userId", userId);
        }
        // 2.8 队伍状态
        Integer status = teamQueryDTO.getStatus();
        TeamStatusEnum teamStatus = TeamStatusEnum.getEnumByValue(status);
        if (teamStatus == null) {
            if (isAdmin || (userId != null && Objects.equals(userId, loginUser.getId()))) {
                // 管理员默认查询所有状态
                queryWrapper.in("status",
                        TeamStatusEnum.PUBLIC.getValue(),
                        TeamStatusEnum.PRIVATE.getValue(),
                        TeamStatusEnum.SECRET.getValue()
                );
                return;
            } else {
                // 非管理员默认查询公开和加密状态
                queryWrapper.in("status",
                        TeamStatusEnum.PUBLIC.getValue(),
                        TeamStatusEnum.SECRET.getValue()
                );
                return;
            }
        }
        // 2.8.1 判断当前用户是否为管理员，不是管理员禁止查看私密队伍
        if (!isAdmin) {
            if (teamStatus.equals(TeamStatusEnum.PRIVATE)) {
                throw new BusinessException(ErrorCode.NO_AUTH, "你无权限查看该状态队伍");
            }
        }
        queryWrapper.eq("status", teamStatus.getValue());
    }

    /**
     * 更新队伍信息
     *
     * @param teamUpdateDTO
     * @param loginUser
     * @return
     */
    @Override
    public boolean updateTeam(TeamUpdateDTO teamUpdateDTO, User loginUser) {
        // 1. 判断当前请求参数是否为空
        if (teamUpdateDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 2. 判断队伍id是否为空
        Long id = teamUpdateDTO.getId();
        Team oldTeam = getTeamById(id);
        // 4. 判断当前用户是否是队伍的创建者或者是否为管理员
        if (!oldTeam.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        // 5. 如果用户传入的新值和老值一致，则不更新（减少数据库压力）
        checkUpdateTeamRules(teamUpdateDTO, loginUser, oldTeam);
        // 6. 更新数据, 返回信息
        Team newTeam = new Team();
        BeanUtils.copyProperties(teamUpdateDTO, newTeam);
        return this.updateById(newTeam);
    }

    /**
     * 修改校验更新数据
     *
     * @param teamUpdateDTO 更新后的队伍信息
     * @param loginUser     当前登录用户
     * @param oldTeam       原队伍信息
     */
    private void checkUpdateTeamRules(TeamUpdateDTO teamUpdateDTO, User loginUser, Team oldTeam) {
        // 1. 队伍名称校验
        String name = teamUpdateDTO.getName();
        if (StringUtils.isNotBlank(name)) {
            // 仅当用户提供了新名称时才进行校验
            if (name.equals(oldTeam.getName())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍名不能与修改前的队伍名一致");
            }
            // 额外校验名称长度
            if (name.length() > 20) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍标题过长");
            }
        }
        // 2. 队伍描述校验
        String description = teamUpdateDTO.getDescription();
        if (StringUtils.isNotBlank(description)) {
            if (description.equals(oldTeam.getDescription())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述不能与修改前的队伍描述一致");
            }
            if (description.length() > 512) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述过长");
            }
        }
//        @Deprecated - 前端默认不允许修改最大队伍人数
//        // 3. 最大人数校验
//        Integer maxNum = teamUpdateDTO.getMaxNum();
//        if (maxNum != null && maxNum > 0) {
//            if (maxNum.equals(oldTeam.getMaxNum())) {
//                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数不能与修改前的队伍人数一致");
//            }
//            if (maxNum < 1 || maxNum > 20) {
//                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数不符合要求");
//            }
//        }
        // 4. 过期时间校验
        LocalDateTime expireTime = teamUpdateDTO.getExpireTime();
        if (expireTime != null) {
            LocalDateTime oldExpireTime = oldTeam.getExpireTime();
            if (expireTime.equals(oldExpireTime)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍过期时间不能与修改前的队伍过期时间一致");
            }
            if (LocalDateTime.now().isAfter(expireTime)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间设置有误");
            }
        }
        // 5. 队伍状态校验
        Integer status = teamUpdateDTO.getStatus();
        if (status == 0) {
            status = null;
        }
        if (status != null) {
            TeamStatusEnum teamStatusEnum = TeamStatusEnum.getEnumByValue(status);
            if (teamStatusEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态错误");
            }
            if (teamStatusEnum.getValue().equals(oldTeam.getStatus())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态不能与修改前的队伍状态一致");
            }
            // 如果设置为私密状态，检查密码
            if (teamStatusEnum.equals(TeamStatusEnum.SECRET)) {
                String password = teamUpdateDTO.getPassword();
                if (StringUtils.isBlank(password)) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码设置有误");
                }
                if (password.length() > 32) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度过长");
                }
            }
        }
    }

    /**
     * 用户加入队伍
     *
     * @param teamJoinDTO
     * @param loginUser
     * @return
     */
    @Override
    public boolean joinTeam(TeamJoinDTO teamJoinDTO, User loginUser) {
        // 1. 校验参数是否为空
        if (teamJoinDTO == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 2. 校验队伍是否存在
        Long teamId = teamJoinDTO.getId();
        Team oldTeam = getTeamById(teamId);
        Long userId = loginUser.getId();
        // 3. 添加分布式锁（加入分布式锁解决线程安全，短时间单个用户快速加入多个队伍问题）
        // 3.1 用户维度锁（防止同一用户并发加入不同队伍）
        String userLockKey = RedisConstant.PROJECT_KEY + RedisConstant.TEAM_KEY + JOIN_TEAM_KEY + userId;
        RLock userLock = redissonClient.getLock(userLockKey);
        // 3.2 队伍维度锁（防止同一队伍并发加入）
        String teamLockKey = RedisConstant.PROJECT_KEY + RedisConstant.TEAM_KEY + JOIN_TEAM_KEY + teamId;
        long waitTime = 1L;
        long leaseTime = 30L;
        RLock teamLock = redissonClient.getLock(teamLockKey);
        try {
            // 获取用户锁
            boolean userLockResult = userLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            if (!userLockResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "操作频繁，请稍后重试");
            }
            // 获取队伍锁
            boolean teamLockResult = teamLock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
            if (!teamLockResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "当前队伍加入人数过多，请稍后重试");
            }
            // 4.校验加入条件
            checkJoinTeamRules(teamJoinDTO, userId, oldTeam, teamId);
            // 5. 新增队伍用户关联信息，返回信息
            UserTeam newUserTeam = new UserTeam();
            newUserTeam.setUserId(userId);
            newUserTeam.setTeamId(teamId);
            newUserTeam.setJoinTime(LocalDateTime.now());
            return userTeamService.save(newUserTeam);
        } catch (InterruptedException e) {
            log.error("joinTeam lock error", e);
            throw new RuntimeException(e);
        } finally {
            // 判断当前锁是否是该线程的锁
            // 按获取相反顺序释放锁
            if (teamLock.isHeldByCurrentThread()) {
                teamLock.unlock();
            }
            if (userLock.isHeldByCurrentThread()) {
                userLock.unlock();
            }
        }
    }

    /**
     * 根据 id 获取队伍信息
     *
     * @param teamId
     * @return
     */
    private Team getTeamById(Long teamId) {
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = this.getById(teamId);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        return team;
    }

    /**
     * 用户加入队伍的参数校验
     *
     * @param teamJoinDTO
     * @param useId
     * @param oldTeam
     * @param teamId
     */
    private void checkJoinTeamRules(TeamJoinDTO teamJoinDTO, Long useId, Team oldTeam, Long teamId) {
        // 3.校验加入条件
        // 3.1 只能加入未满、未过期的队伍
        // 3.1.1 未过期
        LocalDateTime expireTime = oldTeam.getExpireTime();
        if (expireTime != null && expireTime.isBefore(LocalDateTime.now())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该队伍已过期");
        }
        // 3.2 禁止加入状态为私有的队伍
        Integer status = oldTeam.getStatus();
        TeamStatusEnum teamStatusEnum = TeamStatusEnum.getEnumByValue(status);
        if (teamStatusEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态有误");
        }
        if (teamStatusEnum.equals(TeamStatusEnum.PRIVATE)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "禁止加入私密队伍");
        }
        // 3.3 如果加入的队伍是加密的，必须校验密码是否一致
        if (teamStatusEnum.equals(TeamStatusEnum.SECRET)) {
            String userPassword = teamJoinDTO.getPassword();
            if (StringUtils.isBlank(userPassword)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
            }
            String password = oldTeam.getPassword();
            if (!userPassword.equals(password)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
            }
        }
        // 3.4 用户最多创建和加入5个队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("userId", useId);
        long userJoinCount = userTeamService.count(userTeamQueryWrapper);
        if (userJoinCount >= USER_JOIN_MAX_NUM) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户最多创建和加入5个队伍");
        }
        // 3.1.2 未满
        Integer maxNum = oldTeam.getMaxNum();
        userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId", teamId);
        long teamUserCount = userTeamService.count(userTeamQueryWrapper);
        if (teamUserCount > maxNum || teamUserCount < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数已满");
        }
        // 3.5 不能重复加入已经加入的队伍
        userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("userId", useId);
        userTeamQueryWrapper.eq("teamId", teamId);
        long userJoinSameTeamCount = userTeamService.count(userTeamQueryWrapper);
        if (userJoinSameTeamCount > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能重复加入该队伍");
        }
    }


    /**
     * 用户退出队伍
     *
     * @param id
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitTeam(Long id, User loginUser) {
        // 1. 校验参数是否为空
        // 一定程度上可以缓解缓存穿透的问题
        Team oldTeam = getTeamById(id);
        // 3. 校验当前登录用户是否加入了该队伍
        Long userId = loginUser.getId();
        UserTeam queryUserTeam = new UserTeam();
        // 复用了queryWrapper
        queryUserTeam.setUserId(userId);
        queryUserTeam.setTeamId(id);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>(queryUserTeam);
        long isUserJoinTeamCount = userTeamService.count(queryWrapper);
        if (isUserJoinTeamCount == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您未加入该队伍");
        }
        // 4 判断当前队伍剩余人数
        QueryWrapper<UserTeam> countQueryWrapper = new QueryWrapper<>();
        countQueryWrapper.eq("teamId", id);
        long teamUserCount = userTeamService.count(countQueryWrapper);
        // 4.1 如果队伍还剩一人，直接解散队伍
        if (teamUserCount == 1) {
            // 删除队伍数据
            boolean teamDeleteResult = this.removeById(id);
            if (!teamDeleteResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍失败");
            }
        } else {
            // 4.2 如果队伍大于一人，判断当前用户是否是该队队长
            Long oldTeamLeaderId = oldTeam.getUserId();
            if (oldTeamLeaderId == null || oldTeamLeaderId <= 0) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
            if (userId.equals(oldTeamLeaderId)) {
                // 4.3 是队长就按照加入时间顺位将队长给第二位队员
                QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                userTeamQueryWrapper.eq("teamId", id);
                userTeamQueryWrapper.last("ORDER BY id ASC LIMIT 2");
                List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
                if (CollectionUtils.isEmpty(userTeamList) || userTeamList.size() < 2) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队伍数据异常");
                }
                UserTeam nextUserTeamLeader = userTeamList.get(1);
                Long nextUserLeaderId = nextUserTeamLeader.getUserId();
                // 更新新队长信息
                Team updateTeam = new Team();
                updateTeam.setId(id);
                updateTeam.setUserId(nextUserLeaderId);
                boolean updateResult = this.updateById(updateTeam);
                if (!updateResult) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍数据失败");
                }
            }
        }
        // 不论是不是队长,队伍人数剩多少人都要删除用户队伍关联数据
        // 5.返回数据
        return userTeamService.remove(queryWrapper);
    }

    /**
     * 删除（解散）队伍
     *
     * @param id
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeTeam(Long id, User loginUser) {
        // 1. 校验参数是否为空
        // 2. 校验队伍是否存在
        Team oldTeam = getTeamById(id);
        // 3. 校验你是不是队伍的当前队长
        Long userLeaderId = oldTeam.getUserId();
        if (!userLeaderId.equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "当前账户无权限");
        } else {
            // 4. 移除所有队伍的关联信息
            QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("teamId", id);
            boolean removeResult = userTeamService.remove(queryWrapper);
            if (!removeResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队伍信息删除失败");
            }
            // 5. 删除队伍
            // 6. 返回结果
            return this.removeById(id);
        }
    }


}
